#include "EntityState.h"
#include "BoxTweaker.h"
#include "Command.h"
#include "Editor.h"
#include "MoveState.h"
#include "EntityProperty.h"

namespace FinalRendering
{
	namespace Editor
	{
		class AddEntityCommand : public Command
		{
		public:
			RefPtr<Entity> entity;
			void PerformAction(Scene * scene)
			{
				entity->Name = scene->AllocEntityName(entity->Name);
				scene->Entities.Add(entity);
				scene->Modified = true;
				WorldEditor->UpdateViews();
			}

			void UndoAction(Scene * scene)
			{
				scene->Entities.Delete(scene->Entities.Count()-1);
				scene->Modified = true;
				WorldEditor->UpdateViews();
			}
		};

		void EntityState::DrawState_3DView(View3D * view)
		{
			glColor4ub(0,255,0,255);
			DrawAABB(pos-vec3(8.0f,8.0f,8.0f), pos + vec3(8.0f,8.0f,8.0f), view);
		}

		void EntityState::DrawState_LeftView(ViewLeft* view)
		{
			glColor4ub(0,255,0,255);
			DrawAABB(pos-vec3(8.0f,8.0f,8.0f), pos + vec3(8.0f,8.0f,8.0f), view);
		}

		void EntityState::DrawState_TopView(ViewTop * view)
		{
			glColor4ub(0,255,0,255);
			DrawAABB(pos-vec3(8.0f,8.0f,8.0f), pos + vec3(8.0f,8.0f,8.0f), view);
		}

		void EntityState::DrawState_FrontView(ViewFront * view)
		{
			glColor4ub(0,255,0,255);
			DrawAABB(pos-vec3(8.0f,8.0f,8.0f), pos + vec3(8.0f,8.0f,8.0f), view);
		}

		void EntityState::MouseDown(View * view, UIMouseEventArgs & e)
		{
			vec3 p;
			if ((e.Shift & SS_BUTTONMIDDLE))
			{
				WorldEditor->PushState(new MoveState((View *)view, e.X, e.Y, true));
				return;
			}
			if (view->Type != View::vtPerspective)
			{
				view->GetWorldPosFromCursor(e.X,e.Y, pos, p);
				SnapToGrid(view->GridSize, p);
				pos = p;
			}
			State::MouseDown(view, e);
			view->RefreshAllViews();
		}

		void EntityState::MouseUp(View * view, UIMouseEventArgs & e)
		{
			State::MouseUp(view, e);
		}

		void EntityState::MouseMove(View * view, UIMouseEventArgs & e)
		{
			if (MouseDragging)
			{
				if (view->Type != View::vtPerspective)
				{
					vec3 p;
					view->GetWorldPosFromCursor(e.X,e.Y, pos, p);
					SnapToGrid(view->GridSize, p);
					pos = p;
				}
				view->RefreshAllViews();
			}
		}

		void EntityState::KeyDown(View * view, UIKeyEventArgs & e)
		{
			if (e.Key == VK_RETURN)
			{
				AddEntityCommand * cmd = new AddEntityCommand();
				cmd->entity = Entity::CreateEntity(WorldEditor->EntityClassName);
				cmd->entity->GetEntityInterface()->SetName(WorldEditor->Scene->AllocEntityName(WorldEditor->EntityClassName).GetStrPtr());
				if (cmd->entity)
				{
					cmd->entity->SetProperty(L"Position", Editor::Vec3ToString(pos));
					WorldEditor->Execute(cmd);
				}
				else
					delete cmd;
			}
		}


	}
}